#include "mypushbutton.h"

MyPushButton::MyPushButton(QPushButton *parent) : QPushButton(parent)
{
    default_Image = "";
    triggered_Image = "";
}

MyPushButton::MyPushButton(QString default_image, QString triggered_image)
{
    if (triggered_image != "")
        setTriggerImage(triggered_image);

    // 设置并显示默认图片
    setDefaultImage(default_image);
}

bool MyPushButton::useImage(QString img)
{
    // 显示给定图片
    QPixmap pic;

    if (!pic.load(img)) {
        qDebug() << img << "图片加载失败";
        return false;
    }

    this->setFixedSize(pic.width(), pic.height());
    // 设置不规则图片的样式
    this->setStyleSheet("QPushButton{border:0px;}");
    this->setIcon(pic);
    this->setIconSize(QSize(pic.width(), pic.height()));
    return true;
}

bool MyPushButton::setDefaultImage(QString img)
{
    if (useImage(img)) {
        default_Image = img;
        return true;
    }
    return false;
}

bool MyPushButton::setTriggerImage(QString img)
{
    if (!QPixmap().load(img)) {
        qDebug() << img << "图片加载失败";
        return false;
    }
    triggered_Image = img;
    return true;
}

void MyPushButton::mousePressEvent(QMouseEvent *e)
{
    // 仅当按钮有替换图片时，才进行切换
    if (triggered_Image != "") {
        useImage(triggered_Image);
    }

    return QPushButton::mousePressEvent(e);
}

void MyPushButton::mouseReleaseEvent(QMouseEvent *e)
{
    useImage(default_Image);
    return QPushButton::mouseReleaseEvent(e);
}

void MyPushButton::Bouncing()
{
    // 先向下跳跃10px
    QPropertyAnimation *animation1 = new QPropertyAnimation(this, "geometry");
    animation1->setDuration(200);
    // 起始位置
    animation1->setStartValue(QRect(this->x(), this->y(), this->width(), this->height()));
    // 结束位置
    animation1->setEndValue(QRect(this->x(), this->y() + 10, this->width(), this->height()));
    animation1->setEasingCurve(QEasingCurve::OutBounce);
    animation1->start();

    // 再跳回原位
    QPropertyAnimation *animation2 = new QPropertyAnimation(this, "geometry");
    animation1->setDuration(200);
    // 起始位置
    animation2->setStartValue(QRect(this->x(), this->y() + 10, this->width(), this->height()));
    // 结束位置
    animation2->setEndValue(QRect(this->x(), this->y(), this->width(), this->height()));
    animation2->setEasingCurve(QEasingCurve::OutBounce);
    animation2->start();
}
